<?php
namespace appin\cms;

use app\common\exception\AdminException;
use appin\BaseController;
use think\facade\Session;

class Admin extends BaseController
{
    protected $model;
    protected $validate;
    protected $page = 1;
    protected $limit = 20;

    /**
     * 初始化 登陆判断
     */
    public function initialize()
    {
        $this->hasLogin();
        $this->page = $this->request->param('page', 1, 'intval');
        $this->limit = $this->request->param('limit', 20, 'intval');
    }

    /**
     * 管理员是否登陆的判断
     * @return \think\response\Redirect
     */
    public function hasLogin()
    {
        $sessAdmin = Session::get('admin.worker.id');
        if (!$sessAdmin) {
            @header('Location:/admin');
        }
    }

    /**
     * 编辑&新增
     * @return \think\response\View
     */
    public function save()
    {
        $id = $this->request->param('id', 0, 'intval');
        return $this->render('', ['detail' => $this->model::find($id)]);
    }

    /**
     * 处理插入或者编辑的数据
     * @return \think\response\Json|\think\response\View
     */
    public function savedata()
    {
        try {
            $data = $this->request->param();
            $this->initValidatorData($data, $this->validate);
            if ($data['id'] && (int) $data['id'] > 0) {
                $updateO = $this->model::find($data['id']);
                unset($data['id']);
                $updateO->data($data);
                $updateRes = $updateO->save();

                if ($updateRes === false) {
                    throw new AdminException('数据更新失败');
                } else {
                    return json(['state' => 'success', 'data' => $updateRes]);
                }
            } else {
                $insertO = $this->model::create($data);
                return json(['state' => 'success', 'data' => $insertO]);
            }
        } catch (AdminException $ae) {
            return $ae->render();
        }

    }

    /**
     * 删除
     * @return \think\response\Json
     * @throws AdminException
     */
    public function delete()
    {
        $id = $this->request->param('id', 0, 'intval');
        $deleteM = $this->model::find($id);
        if (!$deleteM) {
            throw new AdminException('数据不存在');
        }
        $deleteM->delete();
        return json(['state' => 'success']);
    }

    /**
     * 获取数据
     * @param int $page
     * @param int $limit
     * @return array
     */
    protected function modelDatas($page = 1, $limit = 20, $order = 'sort desc,id desc', $where = '')
    {
        $keyword = $this->request->param('keyword', '', 'strip_tags');
        $total = $this->model::UseKeyword($keyword)->UseWhere($where)->count();
        $rows  = $this->model::UseKeyword($keyword)->UseWhere($where)->page($page, $limit)->select();
        return compact('total', 'rows');
    }

    /**
     * 自动验证数据
     * @param array $data
     * @param bool $scene
     * @return bool
     * @throws \ReflectionException
     */
    protected function initValidatorData( $data = [] , $validate = false, $scene = false )
    {
        try {
            !$scene && $scene = $this->app->appin['action'];
            !$validate && $validate = $this->validate;
            if ( $validate && $this->sences($scene)) {
                $checkData = count($data) === 0 ? $this->request->param() : $data;
                validate($validate)->scene($scene)->check($checkData);
            }
            return true;
        } catch (\Exception $e) {
            throw new AdminException($e->getMessage());
        }

    }

    /**
     * @param $scene
     * @return mixed
     * @throws \ReflectionException
     */
    private function sences($scene)
    {
        $validateClass = new \ReflectionClass( $this->validate );
        $validateO = $validateClass->newInstance();
        return $validateO->hasScene($scene);
    }
}